/*
 * Package il.ac.biu.cs.grossmm.impl.activeData
 * File MergedSet.java
 * 
 * This is a part of presence service framework prototype. 
 * See javadoc for more information.
 *  
 * Copyright (C) 2006 Grossmann Mark
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package il.ac.biu.cs.grossmm.impl.activeData;

import java.util.AbstractCollection;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;

public class MergedSet<N> extends AbstractSet<N> {
	private Set<N>[] nodes;

	private int s = -1;

	MergedSet(Set<N>[] nodes) {
		this.nodes = nodes;
	}

	@Override
	@SuppressWarnings("unchecked")
	public Iterator<N> iterator() {
		return new Iterator<N>() {
			int n = 0;

			Iterator<N> backIt = (Iterator<N>) nodes[0].iterator();;

			public boolean hasNext() {
				while (true) {

					if (backIt.hasNext())
						return true;

					if (n >= 2)
						break;

					backIt = (Iterator<N>) nodes[++n].iterator();
				}

				return false;
			}

			public N next() {
				while (true) {

					if (backIt.hasNext())
						return backIt.next();

					if (n >= 2)
						break;

					backIt = (Iterator<N>) nodes[++n].iterator();
				}

				throw new NoSuchElementException();
			}

			public void remove() {
				throw new UnsupportedOperationException();
			}

		};
	}

	@Override
	public int size() {
		if (s != -1)
			return s;

		s = 0;

		for (int i = 2; i >= 0; i--) {
			s += nodes[i].size();
		}

		return s;
	}
}
